import { ILoading, IToast, IPreviewImage } from '@/types/global';
import { toLang } from '@/utils/lang';

// 存储缓存
export const setStorage = <T>(key: string, value: T) => {
    try {
        const josnString = JSON.stringify(value);
        uni.setStorageSync(key, josnString);
    } catch (error) {
        uni.setStorageSync(key, value);
    }
};

// 获取缓存
export const getStorage = (key: string) => {
    const value = uni.getStorageSync(key);
    try {
        const josnString = JSON.parse(value);
        return josnString;
    } catch (error) {
        return value;
    }
};

// 删除指定缓存
export const removeStorage = (key: string) => {
    uni.removeStorageSync(key);
};

//全部缓存
export const clearStorage = () => {
    uni.clearStorageSync();
};

// 路由跳转
export const NavigateTo = (url: string) => {
    uni.navigateTo({
        url
    });
};

export const RedirectTo = (url: string) => {
    uni.redirectTo({
        url
    });
};

export const ReLaunch = (url: string) => {
    uni.reLaunch({
        url
    });
};

export const SwitchTab = (url: string) => {
    uni.switchTab({
        url
    });
};

export const navigateBack = (delta: number = 1) => {
    const pages = getCurrentPages();
    if (pages.length > delta) {
        uni.navigateBack({
            delta: delta
        });
    } else {
        NavigateTo('/pages/home/index');
    }
};

//开启Toast
export const showToast = <T extends IToast>(obj: T): void => {
    const { title, duration = 2000, icon = 'none', mask, image } = obj;
    setTimeout(() => {
        uni.showToast({
            title,
            duration,
            icon,
            mask,
            image
        });
    }, 500);
};

//隐藏Toast
export const hideToast = () => {
    uni.hideToast();
};

//开启Loading
export const showLoading = (obj = {} as ILoading) => {
    uni.showLoading({
        title: obj.title || toLang('common.loading')+'...',
        ...obj
    });
};

//隐藏Loading
export const hideLoading = () => {
    uni.hideLoading();
};

//预览图片
export const previewImage = (obj = {} as IPreviewImage) => {
    uni.previewImage({
        ...obj,
        urls: obj.urls || [],
        current: obj.current
    });
};

/**
 * 复制文本到剪贴板
 * @param text 要复制的文本
 * @param successMsg 复制成功的提示消息
 * @returns Promise
 */
export const copyToClipboard = (text: string, successMsg = toLang('common.copySuccess')) => {
    return new Promise<void>((resolve, reject) => {
        // 处理空文本情况
        if (!text) {
            uni.showToast({
                icon: 'none',
                title: toLang('common.copyFailed')
            });
            return reject(new Error(toLang('common.copyFailed')));
        }

        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        uni.showToast({
            title: successMsg
        });
        resolve();
    });
};

/**
 * 将图片临时路径转成Buffer文件
 * @param filePath
 * @returns
 */
export const readFileToBuffer = (filePath: string) => {
    return new Promise((resolve, reject) => {
        // 区分平台：H5使用FileReader，其他平台使用FileSystemManager
        // #ifdef H5
        // H5平台：通过XMLHttpRequest读取文件为ArrayBuffer
        const xhr = new XMLHttpRequest();
        xhr.open('GET', filePath, true);
        xhr.responseType = 'arraybuffer'; // 关键：获取二进制数据
        xhr.onload = () => {
            if (xhr.status === 200) {
                const buffer = xhr.response; // ArrayBuffer（可视为Buffer）
                resolve(buffer);
            } else {
                reject(new Error('H5读取文件失败'));
            }
        };
        xhr.onerror = () => reject(new Error('H5网络错误'));
        xhr.send();
        // #endif
        // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
        // 小程序/APP平台：使用FileSystemManager
        const fs = uni.getFileSystemManager();
        fs.readFile({
            filePath: filePath,
            encoding: 'binary', // 二进制编码
            success: (res) => {
                // res.data为二进制字符串，转换为ArrayBuffer（即Buffer）
                const buffer = binaryStringToArrayBuffer(res.data);
                resolve(buffer);
            },
            fail: (err) => reject(err)
        });
        // #endif
    });
};

const binaryStringToArrayBuffer = (binaryString: any) => {
    const len = binaryString.length;
    const buffer = new ArrayBuffer(len);
    const view = new Uint8Array(buffer);
    for (let i = 0; i < len; i++) {
        view[i] = binaryString.charCodeAt(i);
    }
    return buffer;
};

//格式化金额
export const formatAmount = (value: string): string => {
    const num = parseFloat(value);
    return !isNaN(num) ? num.toFixed(2) : '0.00';
};

//格式化金额带符号
export const formatAmountWithSign = (amount: string): string => {
    const num = parseFloat(amount);
    const formatted = formatAmount(amount);
    return num > 0 ? `+${formatted}` : formatted;
};
